//
//  GeneralNet.m
//  NetworkDemo
//
//  Created by InitialC on 2017/5/4.
//  Copyright © 2016年 InitialC. All rights reserved.
//

#import "GeneralNet.h"
#import "MGJRouter.h"
#import "SVProgressHUD.h"

#ifdef DEBUG
#define NetCLog(...) NSLog(__VA_ARGS__)
#else
#define NetCLog(...)
#endif
@interface GeneralNet ()
@property(nonatomic, copy)NSString *requestURL;
@end

@implementation GeneralNet

static NSString *baseURL = nil;
+ (void)load {
        [SVProgressHUD setMinimumDismissTimeInterval: 1.3f];
}
+ (void)setBaseURL:(NSString *)url {
    baseURL = [url copy];
}

- (instancetype)init {
    self = [super init];
    if (self) {
//        self.type = @"post";
        self.baseUrl = baseURL?: BASE_URL;
        self.requestType = HttpRequestUrlType_Post;
//        #if DEBUG
//        self.baseUrl = baseURL?: @"";
//        #else
//        self.baseUrl = baseURL?: @"";
//        #endif
        self.isShowHUD = NO;
        self.isShowFaildError = NO;
        self.isAutoPopLogin = YES;
    }
    return self;
}
- (NSString*)requestURL {
    return [NSString stringWithFormat: @"%@%@",self.baseUrl,self.url];
}
- (void)dealloc {
    
}

- (NSDictionary *)dictionaryWithModel {
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    dic[@"url"] = self.url?: @"";
    if (self.baseUrl) {
        dic[@"url"] = self.requestURL;
    }
    else
    {
        dic[@"url"] = self.url?: @"";
    }
    
    dic[@"parameters"] = self.parameters?: @{};
    if (self.type == nil) {
        switch (self.requestType) {
            case HttpRequestUrlType_Post: 
            {
                self.type = @"post";
            }
                break;
            case HttpRequestUrlType_Get: 
            {
                self.type = @"get";
            }
                break;
            case HttpRequestUrlType_Put: 
            {
                self.type = @"put";
            }
                break;
            case HttpRequestUrlType_Patch: 
            {
                self.type = @"patch";
            }
                break;
            case HttpRequestUrlType_Delete: 
            {
                self.type = @"delete";
            }
                break;
                
            default: 
            {
                self.type = @"post";
            }
                break;
        }
    }
    dic[@"type"] = self.type?: @"post";
    dic[@"isCache"] = @(self.isCache);
    return dic;
    
}
- (NSString*)description {
   return  [NSString stringWithFormat: @"%@",[self dictionaryWithModel] ];
}

- (void)request:(void (^)(id result))completion {

    [self request: completion withFailure: nil];
}
- (void)request:(void (^)(id result))completion withFailure: (void (^)(NSError *error))failure {
    if (self.isShowHUD  ==  YES ) {
//        [SVProgressHUD setDefaultMaskType: SVProgressHUDMaskTypeClear];
//        [SVProgressHUD show];
    }
    
    [MGJRouter openURL: BaseGeneralRequest withUserInfo: [self dictionaryWithModel] completion: ^(id result) {
//        if( [SVProgressHUD isVisible])
//        {
//            [SVProgressHUD dismiss];
//        }
        id results = [self requestEndLogic: result];
        if (results == nil) {
            return ;
        }
        if (([results isKindOfClass: [NSError class]])) {
            if(self.isShowFaildError)
            {
                [SVProgressHUD showErrorWithStatus: [results domain]];
            }
            if (failure) {
                failure(results);
            }
        } else {
            if (completion) {
                completion(results);
            }
        }
        [self requestEnd];
    }];

}
//- (void)request:(NSString *)csrfURL handler:(void (^)(id))completion withFailure:(void (^)(NSError *))failure {
//    NSDictionary *finalDic = [self dictionaryWithModel];
//
//    self.type = self.specType?: @"get";
//    self.parameters = nil;
//    self.url = csrfURL;
//    if (self.specBaseURL != nil) { self.baseUrl = self.specBaseURL;}
//    self.isCache = NO;
//    [self request:^(id result) {
//
//    } withFailure:^(NSError *error) {
//        failure(error);
//    }];
//}

- (id)requestEndLogic:(id)dict {
    
    if ([dict isKindOfClass: [NSError class]])
    {
        NSError *error = dict;
        //取消请求
        if (error.code == NSURLErrorCancelled) {
            return nil;
            
        }
        for(id object in [[dict userInfo] allValues])
        {
            
            if ([object isMemberOfClass: [NSHTTPURLResponse class]])
            {
                if ([object statusCode] == 401)
                {
                    //token 过期；isAutoPopLogin
                    if (_isAutoPopLogin) {
                        [self authorizationTokenInvalid];
                    }
                    NetCLog(@"%@ Token过期\n\n", self.url.description);
                    return [self.url containsString:@"checktoken"] ? error : nil;
                }
            }
        }
        
        NSError *newError = [NSError errorWithDomain: @"服务器请求失败" code: error.code userInfo: error.userInfo];
        NetCLog(@"网络请求错误 == %@",newError);
        return newError;
    } else if (dict[@"code"] == nil) {
        if (dict[@"pk"] != nil) {
            return dict;
        } else {
            NSError *error = [NSError errorWithDomain: @"数据错误" code: 99999 userInfo: nil];
            NetCLog(@"未返回app数据---%@\n\n", error);
            return error;
        }
    } else if ([dict[@"code"] intValue] != 200 &&
               [dict[@"code"] intValue] != 201 &&
               ([dict[@"code"] intValue] > 0 || [dict[@"code"] intValue] < -4)) {
        NSString *domain = dict[@"msg"] == [NSNull null] ? [NSString stringWithFormat:@"未知错误%d", [dict[@"code"] intValue]] : dict[@"msg"];
        NSError *error = [NSError errorWithDomain:domain  code: [dict[@"code"] intValue] userInfo: nil];
        NetCLog(@"请求错误, 返回错误码---%@\n\n", error);
        return error;
        
    } else {
        return dict;
    }
    return dict;
}

- (void)authorizationTokenInvalid {
    [MGJRouter openURL: @"msinger://AuthorizationTokenInvalid" withUserInfo: nil completion: nil];
}

- (void)requestStart {
    
}
- (void)requestEnd {
    
}
- (BOOL)isRequesting {
    return [[MGJRouter objectForURL: @"yanxi://UrlIsRequesting" withUserInfo: @{@"url": self.requestURL}] boolValue];
}

/**
 判断是否请求中
 
 @param url 完整的URL
 @return YES表示请求中，NO表示未请求
 */
+ (BOOL)isRequestingWithURL:(NSString*)url {
    if ([url rangeOfString: @"http"].location != NSNotFound) {
        url = [NSString stringWithFormat: @"%@%@", baseURL, url];
    }
    return [[MGJRouter objectForURL: @"yanxi://UrlIsRequesting" withUserInfo: @{@"url": url}] boolValue];

}
//取消请求
+ (void)cancelRequestURL:(NSString *)url {
    GeneralNet *base = [GeneralNet new];
    if ([url rangeOfString: @"http"].location != NSNotFound) {
        base.baseUrl = @"";
    }
    base.url = url;
    base.type = @"cancel";
    [base request: nil];

}
@end
